
use axum::{
    response::IntoResponse, Json,
};
use crate::adapters::LoginReq;

pub async fn sys_login(Json(req): Json<LoginReq>) -> impl IntoResponse {
    use axum::{
        http::header::HeaderValue,
        http::{header, StatusCode},
    };
    use axum_extra::extract::cookie::{Cookie, SameSite};
    let login_res= crate::auth::login(req.user_no.as_str(), req.user_pwd.as_str()).await;
    if let Err(e) = login_res {
        return axum::response::Response::builder()
            .status(StatusCode::UNAUTHORIZED)
            .body(e.to_string())
            .unwrap();
    }
    let (user, token) = login_res.unwrap();
    let app_conf = shq_common::prelude::get_app_config();
    let hours=app_conf.jwt.expire as i64;
    let cookie = Cookie::build("auth_token", token)
        .path("/")
        .http_only(true)
        .secure(false)
        .same_site(SameSite::Lax)
        .max_age(time::Duration::hours(hours)) // 设置cookie的有效期为12小时
        .finish();
    let mut response = axum::http::Response::builder()
        .status(StatusCode::OK)
        .body(serde_json::to_string(&user).unwrap())
        .unwrap();
    response.headers_mut().append(
        header::SET_COOKIE,
        HeaderValue::from_str(&cookie.to_string()).unwrap(),
    );
    response
}
